<template>
  <div class="page-container">
    <div class="page-header">
      <h2>开题答辩管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="学生姓名">
        <el-input v-model="searchForm.student_name" placeholder="请输入学生姓名" clearable />
      </el-form-item>
      <el-form-item label="题目">
        <el-input v-model="searchForm.topic_title" placeholder="请输入题目" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="待答辩" value="pending" />
          <el-option label="已通过" value="passed" />
          <el-option label="未通过" value="failed" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 答辩列表 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="defenses"
        style="width: 100%"
      >
        <el-table-column prop="student_name" label="学生姓名" />
        <el-table-column prop="topic_title" label="题目" show-overflow-tooltip />
        <el-table-column prop="teacher_name" label="指导教师" />
        <el-table-column prop="defense_time" label="答辩时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="答辩成绩" width="100" />
        <el-table-column prop="comments" label="答辩意见" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="isTeacher && row.status === 'pending'"
              type="primary"
              link
              @click="handleEvaluate(row)"
            >
              评分
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评分对话框 -->
    <el-dialog
      v-model="evaluateDialogVisible"
      title="答辩评分"
      width="500px"
    >
      <el-form
        ref="evaluateFormRef"
        :model="evaluateForm"
        :rules="evaluateRules"
        label-width="100px"
      >
        <el-form-item label="答辩成绩" prop="score">
          <el-input-number
            v-model="evaluateForm.score"
            :min="0"
            :max="100"
            :precision="1"
          />
        </el-form-item>
        <el-form-item label="答辩意见" prop="comments">
          <el-input
            v-model="evaluateForm.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入答辩意见"
          />
        </el-form-item>
        <el-form-item label="答辩结果" prop="status">
          <el-radio-group v-model="evaluateForm.status">
            <el-radio label="passed">通过</el-radio>
            <el-radio label="failed">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="evaluateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEvaluateSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="答辩详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="学生姓名">
          {{ currentDefense.student_name }}
        </el-descriptions-item>
        <el-descriptions-item label="题目">
          {{ currentDefense.topic_title }}
        </el-descriptions-item>
        <el-descriptions-item label="指导教师">
          {{ currentDefense.teacher_name }}
        </el-descriptions-item>
        <el-descriptions-item label="答辩时间">
          {{ currentDefense.defense_time }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDefense.status)">
            {{ getStatusText(currentDefense.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="答辩成绩">
          {{ currentDefense.score }}
        </el-descriptions-item>
        <el-descriptions-item label="答辩意见">
          {{ currentDefense.comments }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useUserStore } from '../../store'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const isTeacher = computed(() => userStore.isTeacher)

// 搜索表单
const searchForm = ref({
  student_name: '',
  topic_title: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const defenses = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 评分表单
const evaluateDialogVisible = ref(false)
const evaluateFormRef = ref(null)
const evaluateForm = ref({
  id: null,
  score: 0,
  comments: '',
  status: 'passed'
})
const evaluateRules = {
  score: [
    { required: true, message: '请输入答辩成绩', trigger: 'blur' }
  ],
  comments: [
    { required: true, message: '请输入答辩意见', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择答辩结果', trigger: 'change' }
  ]
}

// 查看对话框
const viewDialogVisible = ref(false)
const currentDefense = ref({})

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    passed: 'success',
    failed: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待答辩',
    passed: '已通过',
    failed: '未通过'
  }
  return map[status] || status
}

// 获取答辩列表
const fetchDefenses = async () => {
  loading.value = true
  try {
    const response = await fetch(`/api/thesis/proposal-defenses?page=${currentPage.value}&page_size=${pageSize.value}&${new URLSearchParams(searchForm.value)}`)
    const data = await response.json()
    defenses.value = data.items
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取答辩列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchDefenses()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    student_name: '',
    topic_title: '',
    status: ''
  }
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDefenses()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDefenses()
}

// 评分
const handleEvaluate = (row) => {
  evaluateForm.value = {
    id: row.id,
    score: 0,
    comments: '',
    status: 'passed'
  }
  evaluateDialogVisible.value = true
}

// 提交评分
const handleEvaluateSubmit = async () => {
  if (!evaluateFormRef.value) return
  
  await evaluateFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await fetch(`/api/thesis/proposal-defenses/${evaluateForm.value.id}/evaluate`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(evaluateForm.value)
        })
        
        if (response.ok) {
          ElMessage.success('评分成功')
          evaluateDialogVisible.value = false
          fetchDefenses()
        } else {
          throw new Error('评分失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '评分失败')
      }
    }
  })
}

// 查看详情
const handleView = (row) => {
  currentDefense.value = row
  viewDialogVisible.value = true
}

// 初始化
fetchDefenses()
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 